<?php
/**
 * Product: rdc_analysis.
 * Date: 18-7-26
 * Time: 上午8:44
 */

namespace apps\tasksmgr\bizs;

use Phalcon\Dispatcher;
use Phalcon\Http\Request;

class TaskMgrBiz implements \Phalcon\Di\InjectionAwareInterface
{
    private $_di;

    private static $_instance = null;

    private function __construct( $di )
    {
        $this->setDI( $di );
    }

    public static function getInstance( $di = null )
    {
        assert( $di );

        if( !self::$_instance )
        {
            self::$_instance = new TaskMgrBiz( $di );
        }

        return self::$_instance;
    }

    /**
     * 暂时先不做正常的授权管理　先用这个代替
     *
     * @param $request
     *
     * @return bool
     */
    public function checkAccessValid($request )
    {
        assert( $request );

        if( $request->getClientAddress(true) == '127.0.0.1' )
        {
            return true;
        }

        return false;
    }


    private function parseParams( Request $request, Dispatcher $dispatcher )
    {
        if( $request->isGet() )
        {
            return $dispatcher->getParams();
        }
        elseif( $request->isPost() )
        {
            return $request->getPost();
        }

        return [];

    }

    public function dispatchTasks( Request $request, Dispatcher $dispatcher )
    {
        $arrTasks = $this->parseParams( $request, $dispatcher );

        $arrValidTasks = $this->_di->httpServer->getValidTasks( $arrTasks );

        $arrResInfo = [];
        foreach ($arrValidTasks as $taskLabel => $processNum )
        {
            $arrRet = $this->_di->httpServer->dispatchTask( $taskLabel, $processNum );

            foreach( $arrRet as $ret )
            {
                $arrResInfo[] = $ret;
            }
        }

        return $arrResInfo;

    }

    /**
     * Sets the dependency injector
     *
     * @param \Phalcon\DiInterface $dependencyInjector
     */
    public function setDI(\Phalcon\DiInterface $dependencyInjector)
    {
        $this->_di = $dependencyInjector;
    }

    /**
     * Returns the internal dependency injector
     *
     * @return \Phalcon\DiInterface
     */
    public function getDI()
    {
        return $this->_di;
    }
}